local app = require 'app'
local game = app.game.running

local bidder = game.ui.element()

bidder.store_watchers = 
{
    ingame = 
    {
        ['$'] = function()

        end,

        ['请求玩家叫分'] = function(self, store, state, args)
            local player = args.player
            local action_ids = args.action_ids
            local time = args.time

            self:on_bid(player, action_ids, time)
        end,

        ['游戏中'] = function(self, store, state)
            self:hide()
        end
    }
}

function bidder:ctor(ingame)
    self.res = "club.threecard.doudizhu/ui/ingame.b:bidder"
    self.ingame = ingame
    self.actions = {}
end

function bidder:on_injected(bind)
    self.actions[game.util.consts.bid_pass.id] = self.bid_pass
    self.actions[game.util.consts.bid_1.id] = self.bid_1
    self.actions[game.util.consts.bid_2.id] = self.bid_2
    self.actions[game.util.consts.bid_3.id] = self.bid_3

    bind('button.click', self.bid_pass, function() self:click_ivk(game.util.consts.bid_pass.id) end)
    bind('button.click', self.bid_1, function() self:click_ivk(game.util.consts.bid_1.id) end)
    bind('button.click', self.bid_2, function() self:click_ivk(game.util.consts.bid_2.id) end)
    bind('button.click', self.bid_3, function() self:click_ivk(game.util.consts.bid_3.id) end)

    game.utility.button_style.highlight_scale(self.bid_pass)
    game.utility.button_style.highlight_scale(self.bid_1)
    game.utility.button_style.highlight_scale(self.bid_2)
    game.utility.button_style.highlight_scale(self.bid_3)
end

function bidder:click_ivk(id)
    game.kbe.player():bid(id)
    self:hide()
end

function bidder:on_bid(player, action_ids, time)
    local seat = self.ingame.seats[player.seat.local_no]
    self.ingame.clock:start(time, seat.clock_root, nil)
    
    if player.seat.local_no ~= 1 then
        return
    end

    self:show()

    for _, bid in pairs(self.actions) do
        bid.gameObject:SetActive(false)
    end

    for _, id in ipairs(action_ids) do
        if self.actions[id] then
            self.actions[id].gameObject:SetActive(true)
        else
            game.gamelib.log.error('错误的bid action id：'..tostring(id))
        end
    end
end

function bidder:clear_scene()
    self:hide()
end

return bidder